﻿using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using SmartCity.ProcessEngine.API.Domain;
using SmartCity.ProcessEngine.API.ErrorCode;
using SmartCity.ProcessEngine.API.Infrastructrue.Extensions;
using SmartCity.ProcessEngine.API.Infrastructrue.Interfaces;
using SmartCity.ProcessEngine.API.Read.Applications.Commands;
using SmartCity.ProcessEngine.API.Read.DTOS;
using System;
using System.Reflection;

namespace SmartCity.ProcessEngine.API.Read.Applications.CommandHandlers
{
    public class FormTypeQueryCommandHandler : IRequestHandler<FormTypeQueryCommand, APIResult<APIPaging<FormTypeDTO>>>
    {
        private readonly IBaseRespository<WF_FromType> fromtypeRep;
        private readonly IBaseRespository<Industry> industyRep;

        public FormTypeQueryCommandHandler(IBaseRespository<WF_FromType> fromtypeRep, IBaseRespository<Industry> industyRep)
        {
            this.fromtypeRep = fromtypeRep;
            this.industyRep = industyRep;
        }
        /// <summary>
        /// 请求处理
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns>返回任务</returns>
        public Task<APIResult<APIPaging<FormTypeDTO>>> Handle(FormTypeQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<APIPaging<FormTypeDTO>> result = new APIResult<APIPaging<FormTypeDTO>>();
            result.Code = APIResultCode.SearchSuccess;
            result.Message = APIResultCode.SearchSuccess.GetDescription();

            var res = from a in fromtypeRep.GetAll()
                      join b in industyRep.GetAll() on a.IndustryId equals b.IndustryId
                      select new FormTypeDTO
                      {
                          TypeId = a.TypeId,
                          TypeNo = a.TypeNo,
                          TypeName = a.TypeName,
                          IndustryId = a.IndustryId,
                          IndustyName = b.IndustyName
                      };
            if (request.IndustryId > 0)
            {
                res = res.Where(x => x.IndustryId == request.IndustryId);
            }
            if (!string.IsNullOrEmpty(request.TypeName))
            {
                res=res.Where(x=>x.TypeName.Contains(request.TypeName));
            }
            //总条数
            var totalCount = res.Count();
            //总页数
            var totalTow = (int)Math.Ceiling(totalCount * 1.0 / request.Pagsize);
            //排序
            res = res.OrderBy(x => x.TypeId).Skip((request.Pagindex - 1) * request.Pagsize).Take(request.Pagsize);
            APIPaging<FormTypeDTO> paging = new APIPaging<FormTypeDTO>();
            paging.TotalCount = totalCount;
            paging.TotaoTow = totalTow;
            paging.Fdata=res.ToList();
            result.Data= paging;



            return Task.FromResult(result);

        }
    }
}
